package com.example.shuiyin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.shuiyin.dto.ProcessRecordDto;
import com.example.shuiyin.entity.ProcessRecord;
import com.example.shuiyin.exception.AppException;
import com.example.shuiyin.exception.ErrorCode;
import com.example.shuiyin.mapper.ProcessRecordMapper;
import com.example.shuiyin.service.ProcessRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class ProcessRecordServiceImpl implements ProcessRecordService {

    private final ProcessRecordMapper processRecordMapper;

    @Override
    @Transactional
    public ProcessRecord createRecord(ProcessRecord record) {
        processRecordMapper.insert(record);
        return record;
    }

    @Override
    @Transactional
    public ProcessRecord updateRecord(ProcessRecord record) {
        ProcessRecord existingRecord = processRecordMapper.selectById(record.getId());
        if (existingRecord == null) {
            throw new AppException("处理记录不存在", ErrorCode.RESOURCE_NOT_FOUND);
        }
        
        processRecordMapper.updateById(record);
        return record;
    }

    @Override
    public ProcessRecord findById(Long id) {
        if (id == null) {
            throw new AppException("记录ID不能为空", ErrorCode.INVALID_PARAMETER);
        }
        
        ProcessRecord record = processRecordMapper.selectById(id);
        if (record == null) {
            throw new AppException("处理记录不存在", ErrorCode.RESOURCE_NOT_FOUND);
        }
        
        return record;
    }

    // 重命名为getRecordById的方法，改为findById的别名
    public ProcessRecord getRecordById(Long id) {
        return findById(id);
    }

    @Override
    public Page<ProcessRecord> findPageByUserId(Long userId, int pageNum, int pageSize) {
        Page<ProcessRecord> page = new Page<>(pageNum, pageSize);
        return processRecordMapper.selectPageByUserId(page, userId);
    }

    @Override
    public List<ProcessRecord> findRecentByUserId(Long userId, int limit) {
        return processRecordMapper.selectRecentByUserId(userId, limit);
    }

    @Override
    public ProcessRecord findByIdAndUserId(Long id, Long userId) {
        return processRecordMapper.findByIdAndUserId(id, userId);
    }

    @Override
    public Page<ProcessRecordDto> getProcessHistory(Long userId, int page, int limit) {
        // 获取原始处理记录
        Page<ProcessRecord> recordPage = findPageByUserId(userId, page, limit);
        
        // 转换为DTO对象
        List<ProcessRecordDto> dtoList = recordPage.getRecords().stream()
                .map(ProcessRecordDto::fromEntity)
                .collect(Collectors.toList());
        
        // 创建DTO分页对象
        Page<ProcessRecordDto> dtoPage = new Page<>(recordPage.getCurrent(), recordPage.getSize(), recordPage.getTotal());
        dtoPage.setRecords(dtoList);
        
        return dtoPage;
    }

    @Override
    public boolean checkFileAccess(String filename, Long userId) {
        if (filename == null || userId == null) {
            return false;
        }
        
        // 从文件名中提取信息，通常文件名格式会包含用户ID或任务ID信息
        // 这里根据项目的实际文件命名规则来实现权限验证
        try {
            // 方式1：通过数据库查询确认文件归属
            // 假设文件名与数据库中记录的result_url有关联
            QueryWrapper<ProcessRecord> query = new QueryWrapper<>();
            query.eq("user_id", userId)
                 .and(wrapper -> wrapper.like("result_url", "%" + filename + "%"));
            
            return processRecordMapper.selectCount(query) > 0;
            
            // 方式2：如果文件名本身包含用户ID信息，也可以直接解析
            // 例如：如果文件名格式为 "user_{userId}_task_{taskId}.jpg"
            /*
            if (filename.startsWith("user_" + userId + "_")) {
                return true;
            }
            */
        } catch (Exception e) {
            log.error("检查文件访问权限时发生错误", e);
        }
        
        return false;
    }
    
    @Override
    public boolean isFilePublicAccessible(String filename) {
        if (filename == null) {
            return false;
        }
        
        // 可以根据项目需求确定哪些文件允许公开访问
        // 例如：缩略图可能允许公开访问，而原始文件不允许
        
        // 示例：检查文件是否为缩略图
        boolean isThumbnail = filename.contains("_thumb.") || filename.contains("_thumbnail.");
        if (isThumbnail) {
            return true;
        }
        
        // 示例：检查文件是否在公开目录中
        boolean isInPublicDir = filename.startsWith("public/");
        if (isInPublicDir) {
            return true;
        }
        
        // 默认不允许公开访问
        return false;
    }
} 